-- 伍迪辅助
local _G = GLOBAL
local e_util = require "libs/entutil"
local t_util = require "libs/tableutil"
local p_util = require("libs/playerutil")

local _lock
local _SendRPCToServer = _G.SendRPCToServer
function _G.SendRPCToServer(rpc_code, act_code, arg1, ...)
    if act_code == _G.ACTIONS.EAT.code and not _lock then
        if _G.ThePlayer and _G.ThePlayer.prefab == "woodie" then
            local food = type(arg1)=="number" and p_util:GetActiveItem() or arg1
            if e_util:IsValid(food) and food:HasTag("wereitem") then
                _lock = true
                t_util:Pairs(_G.EQUIPSLOTS or {}, function(id, eslot)
                    local equip = p_util:GetEquip(eslot)
                    if equip and not equip:HasTag("backpack") then
                        _G.SendRPCToServer(_G.RPC.ControllerUseItemOnSelfFromInvTile, ACTIONS.UNEQUIP.code, equip)
                    end
                end)
                return _G.ThePlayer:DoTaskInTime(0.2, function()
                    _G.SendRPCToServer(_G.RPC.ControllerUseItemOnSelfFromInvTile, ACTIONS.EAT.code, food)
                    _lock = false
                end)
            end
        end
    end
    return _SendRPCToServer(rpc_code, act_code, arg1, ...)
end

AddPlayerActivatedFunc(function(player, world)
    if player.prefab == "woodie" and world.ismastersim then
        local locomotor = player.components.locomotor
        if locomotor then
            local _PushAction = locomotor.PushAction
            locomotor.PushAction = function(loc, act, ...)
                local act_code = act and act.action and act.action.code
                if act_code == _G.ACTIONS.EAT.code and not _lock then
                    _lock = true
                    local food = act.invobject
                    if e_util:IsValid(food) and food:HasTag("wereitem") then
                        t_util:Pairs(_G.EQUIPSLOTS or {}, function(id, eslot)
                            local equip = p_util:GetEquip(eslot)
                            if equip and not equip:HasTag("backpack") then
                                _G.SendRPCToServer(_G.RPC.ControllerUseItemOnSelfFromInvTile, ACTIONS.UNEQUIP.code, equip)
                            end
                        end)
                        return _G.ThePlayer:DoTaskInTime(0.2, function()
                            p_util:Eat(food)
                            _lock = false
                        end)
                    end
                end
                return _PushAction(loc, act, ...)
            end
        end
    end
end)